import axios from 'axios'
import { Message } from 'qiaonan'
import router from '@/router'
import qs from 'qs'
import {BaseUrl} from './config'
// 基础路径
axios.defaults.baseURL = BaseUrl;
axios.defaults.transformRequest = [(data, config) => {
    if (!config['Content-Type']) {
        return qs.stringify(data);
    }
    const type = config['Content-Type'].toLowerCase();
    if (type.includes('application/json')) {
        return JSON.stringify(data);
    } else if (type.includes('multipart/form-data')) {
        return data;
    } else {
        return qs.stringify(data)
    }
}]
// 请求拦截

axios.interceptors.request.use((config) => {

    let { headers } = config;
    // 设置token
    let header = {
        'user-id': localStorage.getItem('user-id') || '',
        'token': localStorage.getItem('token') || '',
    }
    Object.assign(headers, header);
    // console.log('请求拦截', config)
    return config;
})

// 响应拦截
axios.interceptors.response.use((res) => {
    try {
        const { data } = res
        // console.log('响应拦截', data)
        // return res.data;

        if (!data.flag) {
            Message.error(data.message);
            if (data.code == -1) {
                localStorage.clear();
                router.replace('/login');
            }
            return Promise.reject()
        }
        // 存入token到本地
        res.headers['user-id'] && localStorage.setItem('user-id', res.headers['user-id']);
        res.headers['token'] && localStorage.setItem('token', res.headers['token']);
        return Promise.resolve(data.data);
    }
    catch (err) {
        Message.error('系统繁忙，请稍后再试')
    }
}, (err) => {
    // return err
    Message.error("网络错误!");

    return Promise.reject(err)
})
const http = {
    // get请求
    get(url, data, headers) {
        // 返回的是promise对象
        return axios.get(url, {
            params: data,
            headers
        })
    },

    // post请求
    post(url, data, headers) {
        // 返回的是promise对象
        return axios.post(url, data, {
            headers
        })
    },

    put(url, data = {}, headers) {
        data['_method'] = 'PUT';
        return axios.post(url, data, {
            headers
        });
    },

    delete(url, data, headers) {
        return axios.delete(url, {
            params: data,
            headers
        })
    },
}
export default http;